package com.bianguo.android.iocdemo.view.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.animation.AccelerateInterpolator;
import android.widget.RelativeLayout;

import com.bianguo.android.iocdemo.R;

public class PlayerBgLayout extends RelativeLayout {

    private LayerDrawable mLayerDrawable;
    private ObjectAnimator animator;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public PlayerBgLayout(Context context) {
        this(context, null);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public PlayerBgLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public PlayerBgLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void init(Context context, AttributeSet attrs) {
        Drawable drawable = context.getDrawable(R.drawable.ic_blackground);
        Drawable[] drawables = new Drawable[2];
        drawables[0] = drawable;
        drawables[1] = drawable;
        mLayerDrawable = new LayerDrawable(drawables);
        animator = ObjectAnimator.ofFloat(this, "number", 0f, 1f);
        animator.setDuration(500);
        animator.setInterpolator(new AccelerateInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int alpha = (int)((float) animation.getAnimatedValue() * 225);
                mLayerDrawable.getDrawable(1).setAlpha(alpha);
                setBackground(mLayerDrawable);
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mLayerDrawable.setDrawable(0, mLayerDrawable.getDrawable(1));
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void setForeground(Drawable drawable) {
        mLayerDrawable.setDrawable(1, drawable);
        animator.start();
    }
}
